const mysql2 = require("mysql2");
const os = require("os");

// 获取主机名称
const hostName = os.hostname(); 
const {
  HOST,
  PORT,
  DATABASE,
  USER,
  PASSWORD,
  CONNECTIONLIMIT,
  PROD_HOST,
  PROD_PORT,
  PROD_DATABASE,
  PROD_USER,
  PROD_PASSWORD,
  PROD_CONNECTIONLIMIT,
} = require("../config/server");

let connectionPool; //线程池

// 如果主机名称为本地名
if (hostName === "greenteck") {
  connectionPool = mysql2.createPool({
    host: HOST,
    port: PORT,
    database: DATABASE,
    user: USER,
    password: PASSWORD,
    connectionLimit: CONNECTIONLIMIT,
  });
} else {
  connectionPool = mysql2.createPool({
    host: PROD_HOST,
    port: PROD_PORT,
    database: PROD_DATABASE,
    user: PROD_USER,
    password: PROD_PASSWORD,
    connectionLimit: PROD_CONNECTIONLIMIT,
  });
}

// 2.获取连接是否成功
connectionPool.getConnection((err, connection) => {
  if (err) {
    console.log("获取连接失败", err);
    return;
  }

  // 测试数据库交互
  connection.connect((err) => {
    if (err) {
      console.log("数据库连接失败", err);
    } else {
      console.log("与数据库连接成功，可以操作数据库");
    }
  });
});

// 3.获取数据库连接对象
const connection = connectionPool.promise();

module.exports = connection;
